import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required

from django.utils import simplejson as json

from views.game_server import GameServer
from views.release_notes import ReleaseNotes
from views.admin import Admin


class MainPage(webapp.RequestHandler):
    gs = GameServer()

    def get(self):
        return self.render()

    def post(self):
        return self.render()

    def render(self):
        actions = {}
        actions["register"] = self.gs.register
        actions["unregister"] = self.gs.unregister
        actions['registerrooms'] = self.gs.register_rooms
        actions['ping'] = self.gs.ping

        self.gs.cleanup()

        self.response.headers['Content-Type'] = 'text/xml'

        action = actions.get(self.request.get('act'), self.gs.list)
        format = self.request.get('format', 'old')

        data = {}

        if format == 'old':
            for arg in self.request.arguments():
                if arg.find("_data") != -1:
                    logging.info(arg + " :: " + self.request.get(arg))
                    data[arg[arg.find("[")+1:-1]] = self.request.get(arg)
        elif format == 'json':
            logging.info("Loading json data: " + self.request.get('data'))
            data = json.loads(self.request.get('data'))

        logging.info(self.request.remote_addr)
        data['address'] = data.get('address', None) or self.request.remote_addr

        self.response.out.write(action(data, format))

class ReleaseNotesPage(webapp.RequestHandler):
    rn = ReleaseNotes()

    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(self.rn.show_notes(self.request.get('version', 'list')))

class AdminPage(webapp.RequestHandler):
    admin = Admin()

    def post(self):
        user = users.get_current_user()
        if not users.is_current_user_admin():
            self.error(404)

        self.admin.save_note(self.request.get('version'), self.request.get('notes'))
        self.redirect('/admin')

    @login_required
    def get(self):
        user = users.get_current_user()
        if not users.is_current_user_admin():
            self.error(404)

        actions = {}
        actions['modify_note'] = self.admin.modify_note
        actions['outdate_note'] = self.admin.outdate_note
        actions['remove_server'] = self.admin.remove_server

        self.response.headers['Content-Type'] = 'text/html'

        action = actions.get(self.request.get('act'), self.admin.index)

        self.response.out.write(action(self.request))


class MyIP(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<yourip ip="' + self.request.remote_addr + '"/>')

application = webapp.WSGIApplication([('/', MainPage),
                                      ('/releasenotes', ReleaseNotesPage),
                                      ('/myip', MyIP),
                                      ('/admin', AdminPage),], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()